package com.trt.api.interceptors;

import com.trt.enums.ResponseStatusEnum;
import com.trt.enums.UserStatus;
import com.trt.exception.ApiException;
import com.trt.pojo.AppUser;
import com.trt.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author tanrentao
 * @date 2021-12-02
 * @desc 用户激活状态检查拦截器
 * 发文章，修改文章，删除文章，这些接口都是需要在用户激活以后，才能进行，否则需要提示用户前往[账号设置]去修改信息
 */
public class UserActiveInterceptor extends BaseInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");
        String appUserJson = redisUtils.get(REDIS_USER_INFO + ":" + userId);
        AppUser appUser = null;
        if (StringUtils.isNotBlank(appUserJson)) {
            appUser = JsonUtils.jsonToPojo(appUserJson, AppUser.class);
        } else {
            ApiException.display(ResponseStatusEnum.UN_LOGIN);
            return false;
        }

        if (appUser.getActiveStatus() == null || !UserStatus.ACTIVE.type.equals(appUser.getActiveStatus())) {
            ApiException.display(ResponseStatusEnum.USER_INACTIVE_ERROR);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
